<template>
  <div class="goods" id="goods" name="goods">
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
        <el-breadcrumb-item>全部商品</el-breadcrumb-item>
        <el-breadcrumb-item>分类</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="nav">
      <div class="primary-nav product-nav">
        <div class="title">分类</div>
        <el-tabs
          class="primary-classify"
          v-model="activeName"
          type="card"
          @tab-click="handleTabChange"
        >
          <el-tab-pane
            v-for="item in categoryList"
            :key="item.id"
            :label="item.name"
            :name="String(item.code)"
          />
        </el-tabs>
      </div>
      <div class="product-nav flex">
        <div class="title">品牌</div>
        <div class="brand-container">
          <template
            v-if="Array.isArray(subCategoryList) && subCategoryList.length > 0"
          >
            <el-tabs
              v-model="subActiveName"
              type="card"
              @tab-click="handleSubTabChange"
            >
              <el-tab-pane
                v-for="item in subCategoryList"
                :key="item.id"
                :label="item.name"
                :name="String(item.code)"
              />
            </el-tabs>
          </template>

          <span class="empty-txt" v-else>该分类产品下面还没有品牌数据哦</span>
        </div>
      </div>
    </div>
    <div class="main">
      <div class="list">
        <List :list="product" v-if="product.length > 0"></List>
        <empty v-else></empty>
      </div>
      <div class="pagination" v-if="showPagination">
        <el-pagination
          background
          layout="prev, pager, next"
          :page-size="pageSize"
          :total="total"
          @current-change="currentChange"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>
<script>
import categoryApi from "@/api/category";
import productApi from "@/api/product";
import Empty from "@/components/Empty.vue";
export default {
  name: "Goods",
  components: {
    Empty
  },
  data() {
    return {
      lastTab: null,
      lastSubTab: null,
      categoryList: [],
      subCategoryList: [],
      // 分类id
      categoryID: null,
      subCategoryID: null,
      product: [], // 商品列表
      total: 0, // 商品总量
      pageSize: 8, // 每页显示的商品数量
      currentPage: 1, //当前页码
      activeName: "-1", // 分类列表当前选中的id
      subActiveName: "-1",
      cateMap: {}
    };
  },
  computed: {
    showPagination() {
      return Array.isArray(this.product) && this.product.length > 0;
    }
  },
  async created() {
    await this.getCategory();
    this.getData();
  },
  methods: {
    // 返回顶部
    backtop() {
      const timer = setInterval(function() {
        const top =
          document.documentElement.scrollTop || document.body.scrollTop;
        const speed = Math.floor(-top / 5);
        document.documentElement.scrollTop = document.body.scrollTop =
          top + speed;
        if (top === 0) {
          clearInterval(timer);
        }
      }, 20);
    },
    handleTabChange(tab) {
      if (tab.name == this.lastTab) {
        return;
      }
      this.categoryID = tab.name;
      var targetNode = this.cateMap[this.categoryID];
      this.subCategoryList = targetNode.children;
      // 初始化商品总量和当前页码
      this.total = 0;
      this.currentPage = 1;
      // 更新地址栏链接，方便刷新页面可以回到原来的页面
      this.getData();
      this.lastTab = tab.name;
    },
    handleSubTabChange(subTab) {
      if (this.lastSubTab === subTab.name) {
        return;
      }
      this.subCategoryID = subTab.name;
      // 初始化商品总量和当前页码
      this.total = 0;
      this.currentPage = 1;
      // 更新地址栏链接，方便刷新页面可以回到原来的页面
      this.$router.push({
        path: "/goods",
        query: { categoryID: this.categoryID, subCategory: this.subCategoryID }
      });
      this.lastSubTab = subTab.name;
      this.getData();
    },
    // 页码变化调用currentChange方法
    currentChange(currentPage) {
      this.currentPage = currentPage;
      if (this.search != "") {
        this.getProductBySearch();
      } else {
        this.getData();
      }
      // this.backtop();
    },
    // 向后端请求分类列表数据
    async getCategory() {
      this.cateMap = {};
      let resp = await categoryApi.getCategory();
      if (resp && resp.data) {
        resp.data
          .sort((a, b) => a.parentCode - b.parentCode)
          .forEach(item => {
            this.cateMap[item.code] = item;
            if (item.parentCode != -1) {
              let targetNode = this.cateMap[item.parentCode];
              if (targetNode) {
                if (!Array.isArray(targetNode.children)) {
                  targetNode.children = [item];
                } else {
                  targetNode.children.push(item);
                }
              }
            }
          });
        this.categoryList = Object.values(this.cateMap).filter(
          x => x.parentCode == -1
        );
        if (this.categoryList.length > 0) {
          this.activeName = this.categoryList[0].code.toString();
          this.handleTabChange({ name: this.categoryList[0].code.toString() });
        }
      }
    },
    // 向后端请求全部商品或分类商品数据
    async getData() {
      let resp = await productApi.filter({
        category: this.categoryID,
        subCategory: this.subCategoryID,
        capacity: this.pageSize,
        offset: this.currentPage
      });
      if (resp && resp.data) {
        this.total = resp.data.total;
        this.product = resp.data.data;
      } else {
        this.$message.error("获取产品列表失败!");
      }
    },
    // 通过搜索条件向后端请求商品数据
    async getProductBySearch() {
      let resp = await productApi.search({
        productName: this.search,
        capacity: this.pageSize,
        offset: this.currentPage
      });
      if (resp && resp.data) {
        this.total = resp.data.total;
        this.product = resp.data.data;
      } else {
        this.$message.error("获取产品列表失败!");
      }
    }
  }
};
</script>

<style scoped lang="scss">
.goods {
  background-color: #f5f5f5;
}

::v-deep {
  .el-tabs--card .el-tabs__header {
    border-bottom: none;
  }

  .el-tabs--card > .el-tabs__header .el-tabs__nav {
    border-radius: unset;
  }

  .el-tabs__item.is-active {
    color: $themeColor !important;
  }
  .el-tabs__item:hover {
    color: $themeColor !important;
  }
}

::v-deep {
  .primary-classify {
    .el-tabs__nav {
      border-bottom: 1px solid #e4e7ed;
    }
  }
}

.empty-txt {
  font-size: 14px;
  color: #333;
}

.goods .breadcrumb {
  height: 50px;
  background-color: white;
  display: flex;
  align-items: center;
}

.goods .breadcrumb .el-breadcrumb {
  width: $containerWidth;
  line-height: 30px;
  font-size: 16px;
  margin: 0 auto;
}
/* 面包屑CSS END */

/* 分类标签CSS */
.goods .nav {
  background-color: white;
}
.goods .nav .product-nav {
  width: 1225px;
  height: 40px;
  line-height: 40px;
  margin: 0 auto;
}

.goods .nav .primary-nav {
  margin-bottom: 20px;
}

.nav .product-nav .title {
  width: 50px;
  font-size: 16px;
  font-weight: 700;
  float: left;
}

.flex {
  display: flex;
}

.brand-container {
  flex: 1;
}

/* 分类标签CSS END */

/* 主要内容区CSS */
.goods .main {
  margin: 0 auto;
  max-width: 1225px;
}
.goods .main .list {
  min-height: 650px;
  padding-top: 14.5px;
  margin-left: -13.7px;
  overflow: auto;
}
.goods .main .pagination {
  height: 50px;
  text-align: center;
}

::v-deep {
  .el-pagination.is-background .el-pager li:not(.disabled).active {
    background: $themeColor;
  }
  .el-pagination.is-background .el-pager li:not(.disabled):hover {
    color: $themeColor;
  }
}

.goods .main .none-product {
  color: #333;
  margin-left: 13.7px;
}
/* 主要内容区CSS END */
</style>
